using Microsoft.AspNetCore.Mvc;
using Admin3000.Backend.Api.Repository;
using Admin3000.Backend.Api.Entity;
using System.Linq;
using Admin3000.Backend.Api.Params;
using Admin3000.Backend.Api.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;

namespace Admin3000.Backend.Api.Controllers
{
    //获取token权限
    // [Authorize]

    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private IRepository<Users> _usersRepository;

        private IConfiguration _configuration;

        private TokenParameter _tokenParameter;

        public UsersController(IConfiguration configuration,IRepository<Users> usersRepository)
        {
            _usersRepository=usersRepository;
            _configuration=configuration;
            _tokenParameter=_configuration.GetSection("TokenParameter").Get<TokenParameter>();
        }

        [HttpGet]
        public string Get()
        {
            var pageIndex=int.Parse(Request.Query["pageIndex"][0]);
            var pageSize=int.Parse(Request.Query["pageSize"][0]);
            var Users = _usersRepository.Table;
            var u=Users.Skip((pageIndex-1)*pageSize).Take(pageSize).ToList();
            var res= new
            {
                Code = 1000,
                Data = new {Data=u,Pager=new{pageIndex,pageSize,rowsTotal=Users.Count()}},
                Msg = "获取用户实体成功"
            };
            return JsonHelper.Serialize(res);
        }


        [HttpPost,Route("query")]
        public dynamic Post(QueryData querys)
        {
            var query=querys.query;
            var pageIndex=querys.pageIndex;
            var pageSize=querys.pageSize;
            var rowsTotal=querys.rowsTotal;

            var Users=_usersRepository.Table;

            var resdata = Users.Where(x => x.Username.Contains(query) || x.Remarks.Contains(query)).ToList();
            var u=resdata.Skip((pageIndex-1)*pageSize).Take(pageSize).ToList();
            var res= new
            {
                Code = 1000,
                Data = new {Data=u,Pager=new{pageIndex,pageSize,rowsTotal=Users.Count()}},
                Msg = "查询成功"
            };
            return JsonHelper.Serialize(res);
        }

        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var user = _usersRepository.GetById(id);
            return new
            {
                Code = 1000,
                Database = user,
                Msg = "获取指定用户成功"
            };
        }

        
        [HttpPost]
        public dynamic Post(CreateUser newUser)
        {
            var username = newUser.Username.Trim();
            // var password = newUser.Password.Trim();
            var password=newUser.Password==null?"113":newUser.Password.Trim();

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户名或密码不能为空"
                };
            }

            var user = new Users
            {
                Username = newUser.Username,
                Password = newUser.Password,
                Remarks = newUser.Remarks
            };
            _usersRepository.Insert(user);
            return JsonHelper.Serialize( new
            {
                Code = 1000,
                Data = user,
                Msg = "创建用户成功"
            });
        }

        [HttpPut("{id}")]
        public dynamic Put(int id, CreateUser updateUser)
        {
            var username = updateUser.Username.Trim();
            var password = updateUser.Password.Trim();

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户名或密码不能为空"
                };
            }
            var user = _usersRepository.GetById(id);

            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "要更新的用户不存在，请确认后重试"
                };
            }
            user.Username = updateUser.Username;
            user.Password = updateUser.Password;
            user.Remarks = updateUser.Remarks;

            _usersRepository.Update(user);
            return JsonHelper.Serialize( new
            {
                Code = 1000,
                Data = user,
                Msg = "更新成功"
            });
        }

        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {
            _usersRepository.Delete(id);
            return new
            {
                Code = 1000,
                Data = "",
                Msg = "删除用户成功"
            };
        }

        //所有用户都可访问
        [AllowAnonymous]

        [HttpPost , Route("token")]
        public dynamic GetToken(CreateUser newUser)
        {
            var username = newUser.Username.Trim();
            var password = newUser.Password.Trim();

            var user=_usersRepository.Table.Where(x=>x.Username==username && x.Password==password).FirstOrDefault();

            if(user==null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户名或密码不正确 请确认充实"
                };
            }

            var token=TokenHelper.GenerateToekn(_tokenParameter,user.Username);

            var refreshToken="123456789";

            return new
            { 
                Code = 1000,
                Data = new{Token =token,refreshToken=refreshToken},
                Msg = "登录成功"
            };
        }


        [AllowAnonymous]
        [HttpPost , Route("refreshtoken")]
        public dynamic RefreshToken(RefreshTokenDTO refresh)
        {

            var username=TokenHelper.ValidateToken(_tokenParameter,refresh);

            if(string.IsNullOrEmpty(username))
            {
                return new 
                {
                    Code=1002,
                    Data="",
                    Msg="token验证失败"
                };
            }

            var token=TokenHelper.GenerateToekn(_tokenParameter,username);

            var refreshToken="123456789";

            return new
            { 
                Code = 1000,
                Data = new{Token =token,refreshToken=refreshToken},
                Msg = "创建用户成功"
            };
        }
        
    }
}
























